import { Component, ChangeDetectorRef } from "@angular/core";
import {
  NavController,
  NavParams,
  ActionSheetController,
  AlertController,
  ToastController,
  Platform
} from "ionic-angular";
import { Camera, CameraOptions } from "@ionic-native/camera";
import { appConfig } from "../../providers/config";
import { PhotoViewer } from "@ionic-native/photo-viewer";
import {
  FileTransfer,
  FileUploadOptions,
  FileTransferObject
} from "@ionic-native/file-transfer";
import { File } from "@ionic-native/file";
import { Storage } from "@ionic/storage";
import * as moment from "moment";
import { HttpService } from "../../providers/http.service";
import { HomePage } from "../home/home";

@Component({
  selector: "page-emergency-event-list",
  templateUrl: "emergency-event-list.html"
})
export class EmergencyEventListPage {
  private images: any[] = [];
  private appConfig: any;
  private user: any;
  private elevatorNum: string;
  private elevatorId: string;
  private accidentReason: string;
  constructor(
    public navCtrl: NavController,
    public navParams: NavParams,
    private camera: Camera,
    private ActionSheet: ActionSheetController,
    private photoViewer: PhotoViewer,
    private transfer: FileTransfer,
    private file: File,
    private storage: Storage,
    private httpService: HttpService,
    private alert: AlertController,
    private toast: ToastController,
    public platform: Platform,
    public cd: ChangeDetectorRef
  ) {
    this.appConfig = appConfig;
    //获取当前用户的信息
    this.storage.get("user").then(data => {
      this.user = data;
    });
    this.elevatorNum = navParams.get("elevatorNum");
    this.elevatorId = navParams.get("elevatorId");
    this.accidentReason = "请选择";
  }
  showSelect() {
    let actionSheet = this.ActionSheet.create({
      title: "请选择事故原因",
      cssClass: "action-sheets-basic-page",
      buttons: [
        {
          text: "电梯困人",
          handler: () => {
            this.accidentReason = "电梯困人";
          }
        },
        {
          text: "电梯故障",
          handler: () => {
            this.accidentReason = "电梯故障";
          }
        },
        {
          text: "自然灾害",
          handler: () => {
            this.accidentReason = "自然灾害";
          }
        },
        {
          text: "发生火灾",
          handler: () => {
            this.accidentReason = "发生火灾";
          }
        },
        {
          text: "其他",
          handler: () => {
            this.accidentReason = "其他";
          }
        },
        {
          text: "取消",
          role: "cancel", // will always sort to be on the bottom
          // icon: !this.platform.is("ios") ? "close" : null,
          handler: () => {
            this.accidentReason = "请选择";
          }
        }
      ]
    });
    actionSheet.present();
  }
  doCamera(i) {
    let options: CameraOptions = {
      quality: 85, // destinationType: this.camera.DestinationType.DATA_URL,
      // encodingType: this.camera.EncodingType.JPEG,
      mediaType: this.camera.MediaType.PICTURE,
      targetWidth: 1500,
      targetHeight: 1500,
      correctOrientation: true
    };
    this.camera.getPicture(options).then(
      imageData => {
        const options: FileUploadOptions = {};
        let serverUrl = encodeURI(
          appConfig.IP_URL + appConfig.API.upload
        );
        //let serverUrl =  encodeURI('http://192.168.43.242:8080/upload/base.ctrl');
        options.fileKey = "file";
        options.fileName = "test.jpg";
        options.mimeType = "image/jpeg";
        const fileTransfer: FileTransferObject = this.transfer.create();
        fileTransfer.upload(imageData, serverUrl, options).then(restul => {
          let aa = JSON.parse(restul["response"]);
          if (aa["status"] == 200) {
            if (aa["data"].length > 0) {
              if (i == "c") {
                this.images.push(aa["data"]);
              } else {
                this.images[i] = aa["data"];
              }
            }
          }
          this.cd.detectChanges();
        });
      },
      err => {
        // Handle error
      }
    );
  }

  onHold(param) {
    let actionSheet = this.ActionSheet.create({
      buttons: [
        {
          text: "重拍",
          role: "重拍",
          handler: () => {
            let i = this.images.indexOf(param);
            this.doCamera(i);
          }
        },
        {
          text: "查看大图",
          role: "查看大图",
          handler: () => {
            let url: string = param;
            this.photoViewer.show(url, null, { share: false });
          }
        },
        {
          text: "删除",
          handler: () => {
            let i = this.images.indexOf(param);
            this.images.splice(i, 1);
          }
        },
        {
          text: "取消",
          role: "取消",
          handler: () => {
            //console.log('Cancel clicked');
          }
        }
      ]
    });
    actionSheet.present();
  }

  doConfirm() {
    if (this.images.length <= 0) {
      this.alert
        .create({
          title: "错误",
          message: "请上传图片",
          buttons: ["确认"],
          enableBackdropDismiss: true
        })
        .present();
      return;
    }
    let image = this.images.join(",");
    let data = moment(new Date()).format("YYYYMMDD");
    let param = {
      elevatorNum: this.elevatorNum,
      rescueEndTime: data,
      elevatorId: this.elevatorId,
      rescuePartyId: this.user.partyId,
      picUrl: image,
      accidentReason: this.accidentReason
    };
    this.httpService.emergencyRescueAdd(param).subscribe(data => {
      if (data["status"] == 200) {
        let tt = this.toast.create({
          message: "提交成功",
          duration: 2000,
          position: "top"
        });
        tt.present().then(() => {
          this.navCtrl.setRoot(HomePage);
        });
      } else {
        this.alert
          .create({
            title: "错误",
            message: data["message"],
            buttons: ["确认"],
            enableBackdropDismiss: true
          })
          .present();
      }
    });
  }
}
